import cv2
import os

import time
import multiprocessing as mp

def image_put(q, name, pwd, ip, channel=1):
    cap = cv2.VideoCapture(
        "rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (name, pwd, ip, channel))
    print('DaHua')

    while True:
        q.put(cap.read()[1])
        q.get() if q.qsize() > 1 else time.sleep(0.01)

def image_get(q, window_name, channel):
    start_time = time.time()
    cv2.namedWindow(window_name, flags=cv2.WINDOW_FREERATIO)
    while True:
        frame = q.get()
        frame = cv2.resize(frame, (1080, 720))
        cv2.imshow(window_name, frame)
        now_time = time.time()
        elapsed_time = now_time-start_time
        if (elapsed_time>5):
            start_time = time.time()
            filename = f'frames/{channel}_frame_{str(time.strftime("%Y%m%d-%H%M%S"))}.jpg'
            # cv2.imwrite(filename, frame)
        cv2.waitKey(1)

def run_multi_camera():
    # user_name, user_pwd = "admin", "password"
    user_name, user_pwd = "admin", "@qwertyuiop159"

    camera_ip_l = ["192.168.137.2"] * m
    camera_ip = "192.168.137.2"
    channels = [1, 3]
    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=2*m) for _ in camera_ip_l]

    processes = []
    for queue, channel in zip(queues, channels):
        processes.append(mp.Process(target=image_put, args=(
            queue, user_name, user_pwd, camera_ip, channel)))

        processes.append(mp.Process(target=image_get,
                         args=(queue, camera_ip, channel)))
    # print(processes)

    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()


if __name__ == '__main__':
    m = 2  # 相机个数
    # print(start_time)
    run_multi_camera()
